// pages/goods/goodsList/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [],
    cardList: wx.getStorageSync('cardList') || [],
    pagesize: '10',
    page: 1,
    keyword: "",
    goodsNum: 0,
    url: "https://erp.yilestar.com/",
    showDialog: false,
    goodsStyle: "共0种商品0个",
    num: 0
  },

  // 跳转分类页面
  goClassify() {
    wx.navigateTo({
      url: '../classify/index',
    })
  },

  // 跳转到购物车
  goCard() {
    let cardList = wx.getStorageSync('cardList') || this.data.cardList;
    if (cardList.length == 0) {
      wx.showToast({
        title: '请添加商品',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    cardList.map(item => {
      if (item.goodsNum != 0) {
        this.addCart(item, item.goodsNum)
      } else {
        wx.showToast({
          title: '请添加商品',
          icon: 'none',
          duration: 2000,
        })
        return
      }
    })
    wx.showLoading({
      title: '查看中',
    })
    setTimeout(() => {
      wx.navigateTo({
        url: '../card/index',
      })
      wx.removeStorageSync('cardList')
    }, 1000)
  },

  onLoad(options) {
    // 获取数据 catId

  },

  onShow() {
    this.getData()
    this.getCardData()
  },

  onHide() {
    this.setData({
      goodsList: []
    })
  },

  // scan
  handleScanCode() {
    wx.scanCode({
      success(res) {
        console.log(res)
        wx.showToast({
          icon: "none",
          duration: 2000,
          title: '仅为测试功能~',
        })
      }
    })
  },

  // 创建order
  handleViewDetail() {
    wx.navigateTo({
      url: '../../order/newOrder/index',
    })
  },

  // 获取数据
  getData(e) {
    const self = this;
    const data = {
      // catId: wx.getStorageSync('catId'), // TODO：根据这个id查询暂时没有相关商品
      page: self.data.page,
      pagesize: self.data.pagesize,
      keyword: self.data.keyword
    }
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: 'https://erp.yilestar.com/weapp/shops/getqsShopGoods',
      data,
      method: 'post',
      success: (res) => {
        wx.hideLoading()
        if (res.data.status == -1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
          return;
        }
        const datas = res.data.data.data
        datas.map(item => {
          item.goodsNum = 0;
          item.goodsPrice = item.shopPrice;
          item.active1 = "danger"
        })
        var goodsList = self.data.goodsList.concat(datas)
        self.setData({
          goodsList
        })
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({
          title: '请检查网络是否异常',
          icon: 'none',
        })
      }
    })
  },

  // 监听num的变化并且加入订货清单
  onChange(e) {
    const self = this;
    var num = e.detail;
    const index = e.currentTarget.dataset.index;
    const datas = self.data.goodsList;
    datas[index].goodsNum = num
    let itom = e.currentTarget.dataset.item;
    let cardList = wx.getStorageSync('cardList') || self.data.cardList;
    var res = cardList.some(item => {
        if (item.goodsId == itom.goodsId) {
          return true
        }
      })
    if (res) {
      cardList.map((item,index) => {
        if (num > item.goodsNum && item.goodsId == itom.goodsId) {
            item.goodsNum += 1;
            wx.setStorageSync('cardList', cardList)
        } else if (num < item.goodsNum && item.goodsId == itom.goodsId) {
            item.goodsNum -= 1;
            if (item.goodsNum == 0) {
              cardList.splice(index, 1)
            }
             wx.setStorageSync('cardList', cardList)
          }
      })
    } else {
      wx.setStorageSync('cardList', cardList.concat(itom))
    }
      self.setData({
        goodsList: datas
      })
      self.getCardData()
  },

  // 选择规格
  checkTags(e) {
    const self = this;
    const price = e.currentTarget.dataset.price
    const index = e.currentTarget.dataset.index;
    const active = e.currentTarget.dataset.active;
    // item.active1 = "danger"
    const datas = self.data.goodsList;
    datas[index].goodsPrice = price;
    if (active == 'active1') {
      datas[index][active] = "danger";
      datas[index].active2 = "";
      datas[index].active3 = "";
    }
    if (active == 'active2') {
      datas[index][active] = "danger";
      datas[index].active1 = "";
      datas[index].active3 = "";
    }
    if (active == 'active3') {
      datas[index][active] = "danger";
      datas[index].active2 = "";
      datas[index].active1 = "";
    }
    self.setData({
      goodsList: datas
    })
  },

  // 添加到购物清单
  addCart(e, num) {
    // todo: 添加到购物清单
    const item = e;
    const url = 'https://erp.yilestar.com/weapp/Carts/addCart';
    const self = this;
    const data = {
      tokenId: '5d9df059c27602f5a80e2176d671f9cf', // wx.getStorageSync("tokenId")
      custId: wx.getStorageSync("custId"), // 客户唯一id ; 
      goodsId: item.goodsId,
      unitName: item.goodsUnit, // 规格
      saleTypeId: item.saleTypeId ? item.saleTypeId : 0, // 选择类别，默认为0
      shopPrice: item.shopPrice,
      unitFlg: item.unit_count, //规格
      buyNum: num // 购买数量
    }
    if (!data.buyNum) {
      return
    }
    wx.request({
      url,
      data,
      method: "post",
      success: (res) => {
        wx.showToast({
          title: '添加成功',
        })
      }
    })

  },

  // 获取购物车数据
  getCardData(e) {
    const self = this;
    const datas = wx.getStorageSync('cardList');
    var num = 0;
    if (datas.length != 0) {
      datas.map((item, index) => {
        num += item.goodsNum;
        self.setData({
          goodsStyle: '共' + datas.length + '种商品' + num + '个'
        })
      })
    }else{
      self.setData({
        goodsStyle: '共0种商品0个'
      })
    }
  },

  onPlus(e) {

  },

  onMinus(e) {

  },

  onFocus(e) {
    console.log(e.detail.value)
    const self = this;
    self.setData({
      showDialog: true
    })
  },

  // confirm
  onComfirm(e) {
    console.log(e)
  },
  // cancel
  onCancel(e) {

  },
  onReachBottom() {
    wx.showLoading({
      title: '加载中',
    })
    let page = this.data.page;
    page++
    this.setData({
      page
    })
    this.getData()
  }
})